// tslint:disable-next-line:jsx-no-multiline-js

import React, { Component } from 'react';
import { ConnectState } from '@/models/connect';
import { connect } from 'dva';
import { Icon, Input, Form, Button } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import { Dispatch, AnyAction } from 'redux';
import { LoginParamsType } from '@/services/login';
import styles from './index.css';

interface LoginProps extends FormComponentProps {
  dispatch: Dispatch<AnyAction>;
  form: FormComponentProps['form'];
  submitting: boolean;
}

interface LoginState {}

@connect(({ loading }: ConnectState) => ({
  submitting: loading.effects['login/login'],
}))
class Login extends Component<LoginProps, LoginState> {
  constructor(props: LoginProps) {
    super(props);
  }

  handleSubmit = () => {
    const { validateFields } = this.props.form;
    validateFields((err: any, value: LoginParamsType) => {
      if (!err) {
        const { dispatch } = this.props;
        dispatch({
          type: 'login/login',
          payload: {
            ...value,
          },
        });
      }
    });
  };

  handleGetUsernameInput = () => {
    const { getFieldDecorator } = this.props.form;
    return getFieldDecorator('username', {
      rules: [
        {
          required: true,
          message: '请输入用户名',
        },
      ],
    })(
      <Input
        prefix={<Icon type="XX" className={styles.user} />}
        placeholder="用户名"
        autoComplete="off"
      />,
    );
  };

  handleGetPasswordInput = () => {
    const { getFieldDecorator } = this.props.form;
    return getFieldDecorator('password', {
      rules: [
        {
          required: true,
          message: '请输入密码',
        },
      ],
    })(
      <Input
        prefix={<Icon type="XX" className={styles.pwd} />}
        type="password"
        placeholder="密码"
        autoComplete="off"
      />,
    );
  };

  render() {
    const { submitting } = this.props;
    const formItemLayout = {
      wrapperCol: { span: 24 },
    };
    return (
      <div className={styles.container}>
        <div className={styles.form}>
          <h2 className={styles.title}>{process.env.MAIN_TITLE}</h2>
          <Form className={styles.antdform} onKeyDown={e => e.keyCode === 13 && this.handleSubmit()}>
            <Form.Item {...formItemLayout}>{this.handleGetUsernameInput()}</Form.Item>
            <Form.Item {...formItemLayout}>{this.handleGetPasswordInput()}</Form.Item>
            <Form.Item {...formItemLayout}>
              <Button
                type="primary"
                onClick={this.handleSubmit}
                className={styles['login-form-button']}
                loading={submitting}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  }
}

export default Form.create<LoginProps>()(Login);
